package logic

import (
	"book_srv/book_srv"
	"book_srv/internal/svc"
	"book_srv/models"
	"context"
	"encoding/json"
	"fmt"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookListLogic {
	return &BookListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BookListLogic) BookList(in *book_srv.BookListRequest) (*book_srv.BookListResponse, error) {
	// todo: add your logic here and delete this line
	var date []*book_srv.BookFromList
	key := fmt.Sprintf("%s:%d", in.Title, in.Page)
	get, _ := models.RDB.Get(models.Ctx, key).Result()
	if get == "" {
		var books []struct {
			models.Book
			UserName string
		}
		sql := models.DB.Model(&models.Book{}).Joins("join users on books.user_id = users.id").Select("books.*,users.real_date as user_name").Limit(10).Offset(int(in.Page-1) * 10)
		if in.Title != "" {
			sql = sql.Where("books.title like ?", "%"+in.Title+"%")
		}
		if sql.Scan(&books).Error != nil {
			return nil, fmt.Errorf("服务器繁忙")
		}
		for _, book := range books {
			_get := book_srv.BookFromList{
				Title:    book.Title,
				Author:   book.UserName,
				Image:    book.Image,
				AuthorId: book.AuthorId,
			}
			date = append(date, &_get)
		}
		set, _ := json.Marshal(&date)
		models.RDB.Set(models.Ctx, key, set, 20*time.Hour)
	} else {
		json.Unmarshal([]byte(get), &date)
	}
	var total int64
	if in.Title != "" {
		if models.DB.Model(&models.Book{}).Where("title like ?", "%"+in.Title+"%").Count(&total).Error != nil {
			return nil, fmt.Errorf("服务器繁忙")
		}
	} else {
		if models.DB.Model(&models.Book{}).Count(&total).Error != nil {
			return nil, fmt.Errorf("服务器繁忙")
		}
	}
	return &book_srv.BookListResponse{
		Books: date,
		Total: total,
	}, nil
}
